package sp.whereru;

import java.util.Calendar;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;

public class ReminderService extends IntentService {
	public static int NOTIF_ID = 0;
	private String nTitle;
	private String nMessage;
	private String nTickerMessage;
	private boolean[] courseDays;

	public ReminderService() {
		super("ReminderService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		courseDays = new boolean[7];
		Bundle extras = intent.getExtras();
		String days = extras.getString(CourseAlarmManager.EXTRA_COURSE_DAYS);
		String name = extras.getString(CourseAlarmManager.EXTRA_COURSE_NAME);
		long courseId = extras.getLong(CourseAlarmManager.EXTRA_COURSE_ID);
		int delay = extras.getInt(CourseAlarmManager.EXTRA_COURSE_ALARM_DELAY, 0);
		String[] daysArray = days.split(" ");
		setCourseDays(daysArray);
		
		Calendar calendar = Calendar.getInstance();
		int currentDay = calendar.get(Calendar.DAY_OF_WEEK);
		
		// if today is a day of the week the class takes place
		// then send a notification
		if(courseDays[currentDay - 1] == true) {
			long when = calendar.getTimeInMillis();         
			NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
			
			nTickerMessage = "Go to class!";
			Notification notification = new Notification(R.drawable.ic_notif, nTickerMessage, when);
			notification.defaults = Notification.DEFAULT_ALL;
			notification.flags = Notification.FLAG_AUTO_CANCEL;
			Intent notificationIntent = new Intent(this, DirectionsActivity.class);
			notificationIntent.putExtra(CourseAlarmManager.EXTRA_COURSE_ID, courseId);
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent , 0);
			
			nTitle = name;
			nMessage = name + " in " + delay + " minutes.  Get directions!";
			notification.setLatestEventInfo(getApplicationContext(), nTitle, nMessage, contentIntent);
			nm.notify(NOTIF_ID++, notification);
		}
	}
	
	private void setCourseDays(String[] days) {
		for(String d : days) {
			// courseDays[0] corresponds to Sunday, so we skip it
			if(d.equals("M"))
				courseDays[1] = true;
			else if(d.equals("T"))
				courseDays[2] = true;
			else if(d.equals("W"))
				courseDays[3] = true;
			else if(d.equals("R"))
				courseDays[4] = true;
			else if(d.equals("F"))
				courseDays[5] = true;
			else if(d.equals("S"))
				courseDays[6] = true;
		}
	}
}
